package team.nmsg.ge.system.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSONObject;

import team.nmsg.ge.system.AppServerConstant;


/**
 * @author Guodeqi
 * 全局异常处理器
 *
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

	 private Logger logger =  LoggerFactory.getLogger( GlobalDefaultExceptionHandler.class );
	 
	@ExceptionHandler(value = Exception.class)
	public void defaultErrorHandler(HttpServletRequest req, HttpServletResponse resp ,Exception e) {
		// // If the exception is annotated with @ResponseStatus rethrow it and
		// let
		// // the framework handle it - like the OrderNotFoundException example
		// // at the start of this post.
		// // AnnotationUtils is a Spring Framework utility class.
		// if (AnnotationUtils.findAnnotation(e.getClass(),
		// ResponseStatus.class) != null)
		// throw e;
		//
		// // Otherwise setup and send the user to a default error-view.
		// ModelAndView mav = new ModelAndView();
		// mav.addObject("exception", e);
		// mav.addObject("url", req.getRequestURL());
		// mav.setViewName(DEFAULT_ERROR_VIEW);
		// return mav;

		// 打印异常信息：
		JSONObject retJson = new JSONObject();
		retJson.put("result", false);
		if(e instanceof AuthorizationException){
			retJson.put(AppServerConstant.ERR_KEY_NOPERMIT, true);
		}else{
			retJson.put(AppServerConstant.ERR_KEY_MSG, e.getMessage());
		}
		
		writeJson(retJson , resp);
	}
	
	
	public void writeJson(JSONObject retJson ,  HttpServletResponse httpResp){
		httpResp.setContentType("application/json; charset=utf-8");
		httpResp.setHeader("Cache-Control", "no-cache");
		PrintWriter pw = null;
		try {
			pw = httpResp.getWriter();
			pw.print(retJson);
			pw.flush();
		} catch (IOException e) {
			logger.error("" , e);
		} finally {
			pw.close();
		}
	}
    


}
